import React, { useState } from 'react';
import { payRet } from '@api/submit'
import { TZBANK } from '@/config'
import { PayWayStyle } from '../style'

import { WingBlank, WhiteSpace, Button, Toast } from 'antd-mobile';
import { useSelector } from 'react-redux';
import { OrderGoodsItem } from '@common/goodsItem'


const payway = [
  {
    key: 8,
    type: '微信支付',
    icon: 'https://pay.tzcb.com:11112/icons/publicIcon/icon_WeChat@svg.svg'
  },
  {
    key: 2,
    type: '台行支付(对接中)',
    icon: 'https://pay.tzcb.com:11112/icons/publicIcon/icon_tzyh@svg.svg'
  },
];

const PayWay = (props) => {

  // const [value, setValue] = useState(0)
  const order = useSelector(state => state.order)
  const appConfig = useSelector(state => state.appConfig)
  const [payLoading, setPayLoading] = useState(false)
  const [selectIndex, setSelectIndex] = useState(0)
  const Active = 'https://res.lexiangpingou.cn/images/826/2020/09/u2151MjqJj9sB7721qmU9s9s7UuJm3.png';
  const unActive = 'https://res.lexiangpingou.cn/images/826/2020/10/pGeMlZmBiHH1ZM7dGSmi676gO1xHbz.png'
  return (
    <PayWayStyle>
      <WhiteSpace size="md" />
      <WingBlank>
        <OrderGoodsItem marginStyle={{ marginTop: '.13rem', padding: '.32rem 0' }} className="single-goods"
          goods={order.good} />
      </WingBlank>
      <div className="flex-column">
        {
          payway.map((item, key) => {
            return (
              <WingBlank key={item.key}>
                <button className="payway-btn flex-row" onClick={() => { chosePayway(key) }} disabled={item.key === 2 ? true : false}  >
                  <div className="flex-row payway-btn-left">
                    <img className="payway-icon" src={item.icon} alt="" />
                    {item.type}
                  </div>
                  <img className="payway-active" src={selectIndex === key ? Active : unActive} />
                </button>
              </WingBlank>
            )
          })
        }
      </div>



      <div className="payway-bottom global-bottom-fixed">
        <WingBlank>
          <Button
            onClick={() => { submit() }}
            type='primary'
            loading={payLoading}
            disabled={payLoading}
          > 确认支付 </Button>
        </WingBlank>
      </div>
    </PayWayStyle>
  )

  function submit() {
    setPayLoading(true)
    if (selectIndex === 0) {
      WeiChartPay()
    }
    if (selectIndex === 1) {
      TZBankPay()
    }
  }

  function chosePayway(i) {
    setSelectIndex(i)
    setPayLoading(false)
  }

  function WeiChartPay() {
    let { orderno, tuanid, needprepayprice, realPrice } = order;
    const { uniacid } = appConfig;

    const payParams = {
      orderno: encodeURIComponent(orderno),
      tuanid: encodeURIComponent(tuanid),
      uniacid: encodeURIComponent(uniacid),
      successUrl: encodeURIComponent(window.location.href.replace(window.location.hash, `#/group/`)), // 预付款支付跳转url
      weikuanSuccessUrl: encodeURIComponent(window.location.href.replace(window.location.hash, `#/paysuccess/${orderno}/${realPrice}`)),  // 尾款支付成功跳转url
      failUrl: encodeURIComponent(window.location.href.replace(window.location.hash, `#/`)), // 失败
      realPrice: encodeURIComponent(realPrice)
    }
    window.weiChartAppletPay(payParams)
    // if (res === 'unApplet') {
    //   Toast.info('请在小程序环境中使用', 1)
    // }
    setPayLoading(false)
  }

  async function TZBankPay() {

    let { orderno, tuanid, needprepayprice, realPrice: price, needprepayratio } = order;
    const { uniacid } = appConfig;
    let prepayOrder = []; // 子订单数组，支付成功后要将该数组传给 支付回调接口
    let subOrder1 = orderno + 'y1' // 子订单 1 
    let subOrder2 = orderno + 'y2' // 子订单 2
    let order1Price = parseFloat(needprepayprice)
    let order2Price = (parseFloat(price) - order1Price).toFixed(2)

    let params = {
      uniacid: uniacid,
      orderno: subOrder1,
      price,
      url: window.location.href.replace(window.location.hash, `#/handelpay/${orderno}/${tuanid}`)  // 支付成功回调URL
    }
    // https://pay.tzbank.com:11112/pages/index.html?orderNoList=8442777519307895467&businessCstNo=1266&platMerCstNo=8238509791249432688

    if (needprepayratio !== 0) {
      // 需要预付款
      //  产生两个子订单  分两次请求
      params.price = order1Price
      params.orderno = subOrder1

      console.log(needprepayprice, order1Price)

      payRet(params).then(res => {
        if (res.status === 200) {
          let orderNoList1 = res.data.body.orderFlowNo
          params.orderno = subOrder2
          params.price = order2Price
          console.log(needprepayprice, order2Price)

          payRet(params).then(res => {
            if (res.status === 200) {
              let orderNoList2 = res.data.body.orderFlowNo

              let GO_PAY_URL = TZBANK + `businessCstNo=${uniacid}&orderNoList=${orderNoList1},${orderNoList2}`

              prepayOrder.push({ [subOrder1]: order1Price })
              prepayOrder.push({ [subOrder2]: order2Price })
              localStorage.setItem('orderNoList', JSON.stringify([orderNoList1, orderNoList2]))
              localStorage.setItem('prepayOrder', JSON.stringify(prepayOrder))

              console.log(GO_PAY_URL)

              window.location.href = GO_PAY_URL // 跳转到台行收银台
              setPayLoading(false)

            } else {
              Toast.fail('服务器错误', 1)
              setPayLoading(false)

            }
          })
        }
      })
    } else {
      //  不需要预付款
      let res = await payRet(params)

      if (res.status === 200) {
        let orderNoList = res?.data?.body?.orderFlowNo

        let GO_PAY_URL = TZBANK + `businessCstNo=${uniacid}&orderNoList=${orderNoList}`

        prepayOrder.push({ [subOrder1]: price })
        localStorage.setItem('orderNoList', JSON.stringify([orderNoList]))
        localStorage.setItem('prepayOrder', JSON.stringify(prepayOrder))

        window.location.href = GO_PAY_URL  // 跳转到台行收银台
        setPayLoading(false)


      } else {
        Toast.fail('服务器错误', 1)
        setPayLoading(false)

      }
    }
  }
}





export default PayWay;